package com.example.patient.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.common.entity.*;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.UIDUtils;
import com.example.patient.dto.req.DoFollowrReq;
import com.example.patient.dto.req.MyFollowrDetailReq;
import com.example.patient.dto.req.WcJsapiTicketReq;
import com.example.patient.dto.resp.*;
import com.example.patient.jpa.*;
import com.example.patient.mapper.HomeMapper;
import com.example.patient.service.HomeService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wxy
 * @Date 2021/1/18 13:08
 * @Version 1.0
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Resource
    private UIDUtils uidUtils;
    @Resource
    private WxMpService wxMpService;

    @Resource
    private HomeMapper homeMapper;

    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private HospitalDepartmentRepository hospitalDepartmentRepository;
    @Resource
    private FollowrQuestionMainRepository followrQuestionMainRepository;
    @Resource
    private QuestionRepository questionRepository;
    @Resource
    private AnswerRepository answerRepository;

    /**
     * 首页信息
     */
    @Override
    public IndexDataResp IndexData() {
        Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
        CheckUtils.checkNull(hospital, new ApiException(1, "未查找到医院"));

        IndexDataResp.HospitalResp hospitalResp = new IndexDataResp.HospitalResp();
        hospitalResp.setName(hospital.getName());
        hospitalResp.setBanner(hospital.getBanner());
        hospitalResp.setAddress(hospital.getAddress());
        hospitalResp.setLevel(hospital.getLevel());

        List<IndexDataResp.DepResp> depRespList = new ArrayList<>();
        List<HospitalDepartment> departmentList = hospitalDepartmentRepository.findByDisableAndIsRecommend(Boolean.FALSE, Boolean.TRUE);
        if (!CollectionUtils.isEmpty(departmentList)) {
            depRespList = departmentList.stream().map(m -> {
                IndexDataResp.DepResp resp = new IndexDataResp.DepResp();
                resp.setId(m.getId());
                resp.setName(m.getName());
                resp.setLabel(m.getLabel());
                return resp;
            }).collect(Collectors.toList());
        }

        List<IndexDataResp.DocResp> docRespList = new ArrayList<>();
        List<Map<String, Object>> mapList = homeMapper.findIndexDataRespDocResp();
        if (!CollectionUtils.isEmpty(mapList)) {
            docRespList = mapList.stream().map(m -> {
                String dcId = null == m.get("DCID") ? "" : m.get("DCID").toString();
                String head = null == m.get("Head") ? "" : m.get("Head").toString();
                String name = null == m.get("Name") ? "" : m.get("Name").toString();
                String title = null == m.get("Title") ? "" : m.get("Title").toString();
                String dName = null == m.get("dName") ? "" : m.get("dName").toString();
                String praise = null == m.get("Praise") ? "" : m.get("Praise").toString();
                IndexDataResp.DocResp resp = new IndexDataResp.DocResp();
                resp.setDcId(dcId);
                resp.setHead(head);
                resp.setName(name);
                resp.setTitle(title);
                resp.setDName(dName);
                resp.setPraise(praise);
                return resp;
            }).collect(Collectors.toList());
        }

        String notice = "";
        HDoctorNotice hDoctorNotice = homeMapper.findHDoctorNoticeTop();
        if (!ObjectUtils.isEmpty(hDoctorNotice)) {
            notice = hDoctorNotice.getContents();
        }

        IndexDataResp resp = new IndexDataResp();
        resp.setHospital(hospitalResp);
        resp.setDep(depRespList);
        resp.setDoc(docRespList);
        resp.setNotice(notice);
        return resp;
    }

    /**
     * 医院公告列表
     */
    @Override
    public List<NoticeListResp> NoticeList() {
        List<NoticeListResp> list = new ArrayList<>();
        List<HDoctorNotice> data = homeMapper.findNoticeList();
        if (!CollectionUtils.isEmpty(data)) {
            list = data.stream().map(m -> {
                NoticeListResp resp = new NoticeListResp();
                resp.setContents(m.getContents());
                resp.setCreateTime(m.getCreateTime());
                return resp;
            }).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 执业信息
     */
    @Override
    public HospitalInfoResp HospitalInfo() {
        HospitalInfoResp resp = new HospitalInfoResp();
        Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
        if (!ObjectUtils.isEmpty(hospital)) {
            resp.setAwarded(hospital.getAwarded());
            resp.setLevel(hospital.getLevel());
            resp.setLicenseURL(hospital.getLicenseUrl());
            resp.setName(hospital.getName());
            resp.setNetDiagnosis(hospital.getNetDiagnosis());
        }
        return resp;
    }

    /**
     * 科室
     */
    @Override
    public DepListResp DepList() {
        List<DepListResp.DepResp> list = new ArrayList<>();
        List<HospitalDepartment> departmentList = hospitalDepartmentRepository.findByDisable(Boolean.FALSE);
        if (!CollectionUtils.isEmpty(departmentList)) {
            list = departmentList.stream().map(m -> {
                DepListResp.DepResp resp = new DepListResp.DepResp();
                resp.setId(m.getId());
                resp.setName(m.getName());
                resp.setLabel(m.getLabel());
                return resp;
            }).collect(Collectors.toList());
        }
        DepListResp resp = new DepListResp();
        resp.setDep(list);
        return resp;
    }

    /**
     * 随访列表
     */
    @Override
    public List<MyFollowrListResp> MyFollowrList() {
        Long uid = uidUtils.getUid();
        List<MyFollowrListResp> dataList = homeMapper.findMyFollowrList(uid);
        dataList = dataList.stream().peek(p -> {
            long age = DateUtil.betweenYear(p.getBirthday(), new Date(), Boolean.FALSE);
            p.setAge((int) age);
        }).collect(Collectors.toList());
        return dataList;
    }

    /**
     * 随访详情
     */
    @Override
    public MyFollowrDetailResp MyFollowrDetail(MyFollowrDetailReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long fid = CheckUtils.checkNullReturn(req.getFID(), new ApiException(1, "随访id不能为空"));

        FollowrQuestionMain followrQuestionMain = followrQuestionMainRepository.findById(fid).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        List<Question> questionList = questionRepository.findAllByFidOrderByQidAsc(followrQuestionMain.getFid());
        List<Answer> answerList = answerRepository.findByFid(followrQuestionMain.getFid());

        List<MyFollowrDetailResp.QAListResp> qaListRespList = new ArrayList<>();

        questionList.forEach(c -> {

            List<MyFollowrDetailResp.AnswerResp> answerRespList = answerList.stream()
                    .filter(f -> f.getQid().equals(c.getQid()))
                    .map(m -> {
                        MyFollowrDetailResp.AnswerResp answerResp = new MyFollowrDetailResp.AnswerResp();
                        answerResp.setId(m.getId());
                        answerResp.setFid(m.getFid());
                        answerResp.setAItem(m.getAItem());
                        answerResp.setChk(m.getChk());
                        return answerResp;
                    }).collect(Collectors.toList());

            MyFollowrDetailResp.QAListResp qaListResp = new MyFollowrDetailResp.QAListResp();
            qaListResp.setQContent(c.getQContent());
            qaListResp.setQType(c.getQType());
            qaListResp.setAnswer(answerRespList);
            qaListRespList.add(qaListResp);
        });

        MyFollowrDetailResp resp = new MyFollowrDetailResp();
        resp.setTName(followrQuestionMain.getTName());
        resp.setQaList(qaListRespList);
        return resp;
    }

    /**
     * 完成随访
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public DoFollowrResp DoFollowr(List<DoFollowrReq> reqList) {
        CheckUtils.checkNull(reqList, new ApiException(1, "对象不能为空"));
        Long fid = reqList.get(0).getFID();

        List<Long> ids = reqList.stream().map(DoFollowrReq::getID).collect(Collectors.toList());
        List<Answer> answerList = answerRepository.findByIdIn(ids);
        answerList = answerList.stream().peek(p -> {
            p.setChk(true);
            DoFollowrReq req = reqList.stream()
                    .filter(f -> f.getID().equals(p.getId()))
                    .findFirst()
                    .orElseThrow(() -> new ApiException(1, "未查询到数据"));
            if (3 == req.getQType()) {
                p.setAItem(req.getAItem());
            }
        }).collect(Collectors.toList());
        answerRepository.saveAll(answerList);

        FollowrQuestionMain followrQuestionMain = followrQuestionMainRepository.findById(fid).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        followrQuestionMain.setAnswer(true);
        followrQuestionMain.setFinishTime(new Date());
        followrQuestionMainRepository.save(followrQuestionMain);

        DoFollowrResp resp = new DoFollowrResp();
        resp.setSave(Boolean.TRUE);
        return resp;
    }

    /**
     * 微信JsTicket签名
     */
    @Override
    public Object WcJsapiTicket(WcJsapiTicketReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String url = CheckUtils.checkNullReturn(req.getUrl(), new ApiException(1, "url不能为空"));
        try {
            return wxMpService.createJsapiSignature(url);
        } catch (WxErrorException e) {
            throw new ApiException(1, e.getMessage());
        }
    }
}
